package com.outsourcing.bottle.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.ServiceUtils;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;
import com.outsourcing.bottle.widget.CustomZoomControls;

public class MapViewActivity extends BasicActivity implements BasicUIEvent,
		Callback, OnClickListener {

	private static final int EXEU_LOCATION = 0;
	private static final int EXEU_MY_LOCATION = 1;
	private static final int EXEU_LOCATION_FAILED = 2;
	Handler handler;
	ImageView topbar_back;
	ImageView topbar_menu;
	ImageView iv_map;
	TextView tv_location;
	ImageButton ib_location;

	float longitude, latidute;
	String location;
	Bitmap bitmap = null;
	private CustomZoomControls zoomControls;
	private int zoom = 15;
	private LocationManager locationManager;
	private String bestProvider;
	private Location locationResult;
	/** 0:传过来的位置 1：我的位置 */
	private int locationType = 0;

	@Override
	protected void onCreate(Bundle paramBundle) {	
		super.onCreate(paramBundle);
		setContentView(R.layout.map_view);
		handler = new Handler(this);
		longitude = getIntent().getFloatExtra("longitude", 0);
		latidute = getIntent().getFloatExtra("latidute", 0);
		location = getIntent().getStringExtra("location");

		topbar_back = (ImageView) findViewById(R.id.topbar_back);
		topbar_back.setOnClickListener(this);
		topbar_menu = (ImageView) findViewById(R.id.topbar_menu);
		topbar_menu.setVisibility(View.GONE);
		iv_map = (ImageView) findViewById(R.id.iv_map);

		tv_location = (TextView) findViewById(R.id.tv_location);
		tv_location.setText(location);
		tv_location.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				locationType = 0;
				UICore.eventTask(MapViewActivity.this, MapViewActivity.this,
						EXEU_LOCATION, "", null);
			}
		});
		ib_location = (ImageButton) findViewById(R.id.ib_location);
		ib_location.setOnClickListener(this);

		zoomControls = (CustomZoomControls) findViewById(R.id.zoomcontrols);
		zoomControls.setOnZoomOutClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				zoom -= 1;
				if (locationType == 1) {
					UICore.eventTask(MapViewActivity.this, MapViewActivity.this,
							EXEU_MY_LOCATION, "", null);
				} else {
					UICore.eventTask(MapViewActivity.this,
							MapViewActivity.this, EXEU_LOCATION, "", null);
				}
			}
		});

		zoomControls.setOnZoomInClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				zoom += 1;
				if (locationType == 1) {
					UICore.eventTask(MapViewActivity.this, MapViewActivity.this,
							EXEU_MY_LOCATION, "", null);
				} else {
					UICore.eventTask(MapViewActivity.this,
							MapViewActivity.this, EXEU_LOCATION, "", null);
				}	
			}
		});

		UICore.eventTask(this, this, EXEU_LOCATION, "", null);
	}

	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case EXEU_LOCATION:
			doLocation(latidute, longitude, zoom);
			break;
		case EXEU_MY_LOCATION:
			locationCurrent();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (null != bitmap) {
			bitmap.recycle();
			bitmap = null;
		}
	}

	private void doLocation(float latitude, float longitude, int zoom) {
		String language = AppContext.language == 1?"zh":"en";
		String url_map = UrlConfig.map_static_url + "?center=" + latidute + ","
				+ longitude + "&zoom=" + zoom + "&size=" + CanvasWidth + "x"
				+ (CanvasHeight-50-50)
				+ "&sensor=false&language="+language+"&mobile=true&markers=color:red%7Clabel:C%7C"
				+ latidute + "," + longitude;
		ServiceUtils.dout(url_map);
		bitmap = HttpUtils.getMapBitmapFromUrl(this, url_map);
		if (null != bitmap) {
			Message message = Message.obtain(handler);
			message.what = EXEU_LOCATION;
			handler.sendMessage(message);
		}
	}

	private void locationCurrent() {
		if (null!=locationResult) {
			longitudeCurrent = locationResult.getLongitude();
			latitudeCurrent = locationResult.getLatitude();
		}else {
			requestTelLocation();
		}
		if (longitudeCurrent>0&&latitudeCurrent>0) {
			String language = AppContext.language == 1?"zh":"en";
			String url_map = UrlConfig.map_static_url + "?center="
					+ latitudeCurrent + ","
					+ longitudeCurrent + "&zoom=" + zoom + "&size="
					+ CanvasWidth + "x" + (CanvasHeight - 50-50)
					+ "&sensor=false&language="+language+"&mobile=true&markers=color:red%7Clabel:C%7C"
					+ latitudeCurrent + ","
					+ longitudeCurrent;
			ServiceUtils.dout(url_map);
			bitmap = HttpUtils.getMapBitmapFromUrl(this, url_map);
			if (null != bitmap) {
				Message message = Message.obtain(handler);
				message.what = EXEU_LOCATION;
				handler.sendMessage(message);
			}
		}else {
			Message message = Message.obtain(handler);
			message.what = EXEU_LOCATION_FAILED;
			handler.sendMessage(message);
		}
	
	}

	private Criteria getCriteria() {
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_COARSE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		return criteria;
	}

	LocationListener locationListener = new LocationListener() {
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {

		}

		@Override
		public void onProviderEnabled(String provider) {

		}

		@Override
		public void onProviderDisabled(String provider) {

		}

		@Override
		public void onLocationChanged(Location location) {

		}
	};
	private double longitudeCurrent;
	private double latitudeCurrent;
	private void requestLocation(JSONObject object) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://www.google.com/loc/json");
		try {
			StringEntity entity = new StringEntity(object.toString());
			post.setEntity(entity);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		try {
			HttpResponse resp = client.execute(post);
			HttpEntity entity = resp.getEntity();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					entity.getContent()));
			StringBuffer buffer = new StringBuffer();
			String result = br.readLine();
			while (result != null) {
				buffer.append(result);
				result = br.readLine();
			}
			JSONObject obj = new JSONObject(buffer.toString());
			JSONObject locationObj = obj.getJSONObject("location");
			latitudeCurrent = locationObj.getDouble("latitude");
			longitudeCurrent = locationObj.getDouble("longitude");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	private void requestTelLocation() {
		TelephonyManager mTelMan = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		String operator = mTelMan.getNetworkOperator();
		String mcc = operator.substring(0, 3);
		String mnc = operator.substring(3);

		GsmCellLocation location = (GsmCellLocation) mTelMan.getCellLocation();
		int cid = location.getCid();
		int lac = location.getLac();

		JSONObject tower = new JSONObject();
		try {
			tower.put("cell_id", cid);
			tower.put("location_area_code", lac);
			tower.put("mobile_country_code", mcc);
			tower.put("mobile_network_code", mnc);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		JSONArray array = new JSONArray();
		array.put(tower);
		List<NeighboringCellInfo> list = mTelMan.getNeighboringCellInfo();
		Iterator<NeighboringCellInfo> iter = list.iterator();
		NeighboringCellInfo cellInfo;
		JSONObject tempTower;
		while (iter.hasNext()) {
			cellInfo = iter.next();
			tempTower = new JSONObject();
			try {
				tempTower.put("cell_id", cellInfo.getCid());
				tempTower.put("location_area_code", cellInfo.getLac());
				tempTower.put("mobile_country_code", mcc);
				tempTower.put("mobile_network_code", mnc);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			array.put(tempTower);
		}

		JSONObject object = createJSONObject("cell_towers", array);
		requestLocation(object);
	}
	private JSONObject createJSONObject(String arrayName, JSONArray array) {

		JSONObject object = new JSONObject();
		try {
			object.put("version", "1.1.0");
			object.put("host", "maps.google.com");
			object.put(arrayName, array);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return object;
	}
	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case EXEU_LOCATION:
			iv_map.setImageBitmap(bitmap);
			break;
		case EXEU_LOCATION_FAILED:
			onToast(TextUtil.R("location_error"));
			break;
		default:
			break;
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.topbar_back:
			finish();
			break;
		case R.id.ib_location:
			locationType = 1;
			locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			bestProvider = locationManager
					.getBestProvider(getCriteria(), false);
			if (bestProvider == null) {
				bestProvider = LocationManager.NETWORK_PROVIDER;
			}
			locationManager.requestLocationUpdates(bestProvider, 2000, 0,
					locationListener);
			locationResult = locationManager.getLastKnownLocation(bestProvider);
			UICore.eventTask(MapViewActivity.this, MapViewActivity.this,
					EXEU_MY_LOCATION, "", null);
			break;
		default:
			break;
		}

	}

}
